package com.itheima.mythread.Demo6;

public class MyRunnable implements Runnable {
    private static int tickets = 30;

    @Override
    public void run() {
        while (true) {
            if ("一号窗口".equals(Thread.currentThread().getName())) {
                boolean result = synchronizedMethod();
                if (result) {
                    break;
                }
            }

            if ("二号窗口".equals(Thread.currentThread().getName())) {
                synchronized (MyRunnable.class) {
                    if (tickets < 0) {
                        break;
                    } else {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + "正在售票,还剩" + tickets + "张票");
                        tickets--;
                    }
                }
            }
        }
    }

    private static synchronized boolean synchronizedMethod() {
        if (tickets < 0) {
            return true;
        } else {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "正在售票,还剩" + tickets + "张票");
            tickets--;
            return false;
        }
    }
}
